package com.budwk.app.sqfwV2.service.weiqingmen;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.SqfwSmsMsgService;
import com.budwk.app.sqfw.vo.DownDataVo;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.config.ExcelGeneratorConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.excelService.CompleteFlowExcelService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelRowDataParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.weiqingmen.SafetyCheckDTO;
import com.budwk.app.sqfwV2.enums.weiqingmen.SafetyCheckEnum;
import com.budwk.app.sqfwV2.generator.weiqingmen.*;
import com.budwk.starter.security.utils.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-04-01
 * <p>
 * 威清门消防安全排查 SafetyCheck
 */
@IocBean
public class SafetyCheckExcelService extends CompleteFlowExcelService {

    @Inject
    SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    SqfwSmsMsgService sqfwSmsMsgService;

    /**
     * app端下载 2.0版本
     * @param reqVo
     * @return
     */
    public DownDataVo<ResultOfExcelGenerator> createExcel(DownExcelLedgerReqVo reqVo) {
        List<ExcelCreateConfig> excelConfigList = new ArrayList<>();
        if (reqVo.isDownTemplate()) {
            ExcelCreateConfig config = new ExcelCreateConfig();
            config.setFileIdentity(reqVo.getFileCode());
            config.setOnlyGenerateTemplateFlag(true);
            excelConfigList.add(config);
        } else {
            Map<String,Object> param = new HashMap<>();
            param.put("start", reqVo.getFillStartDate());
            param.put("end", reqVo.getFillEndDate());
            param.put("shopInfoId", reqVo.getShopInfoId());
            if (reqVo.isCheckData()) {
                List<SafetyCheckEnum> safetyCheckEnumList = SafetyCheckEnum.getExcel();
                safetyCheckEnumList.sort(Comparator.comparing(SafetyCheckEnum::getOrder)); // 升序
                for (SafetyCheckEnum excel : safetyCheckEnumList) {
                    ExcelCreateConfig config = new ExcelCreateConfig();
                    config.setFileIdentity(excel.getCode());
                    config.setCreateExcelFileFlag(false);
                    config.setParam(param);
                    excelConfigList.add(config);
                }
            } else {
                ExcelCreateConfig config = new ExcelCreateConfig();
                config.setFileIdentity(reqVo.getFileCode());
                config.setCreateExcelFileFlag(true);
                config.setParam(param);
                excelConfigList.add(config);
            }
        }

        ExcelCreateConfig config = excelConfigList.get(0);

        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getCreateBy, "=", SecurityUtil.getUserId());
        cnd.and(Sqfw_formSummary_new::getType, "=", SqfwFormSummaryConstants.safety_check);
        if ((config.getParam().get("start") != null && StringUtils.isNotBlank(config.getParam().get("start").toString()))) {
            cnd.and(Sqfw_formSummary_new::getFillDate, ">=", config.getParam().get("start"));
        }
        if ((config.getParam().get("end") != null && StringUtils.isNotBlank(config.getParam().get("end").toString()))) {
            cnd.and(Sqfw_formSummary_new::getFillDate, "<=", config.getParam().get("end") + " 23:59:59");
        }
        if ((config.getParam().get("shopInfoId") != null && StringUtils.isNotBlank(config.getParam().get("shopInfoId").toString()))) {
            cnd.and(Sqfw_formSummary_new::getShopsBaseInfoId, "=", config.getParam().get("shopInfoId"));
        }

        List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query("id", cnd);

        List<String> ids = formSummaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList());

        CompleteFlowExcelParamForController paramForController = new CompleteFlowExcelParamForController();
        paramForController.setExcelCreateConfigList(excelConfigList);
        paramForController.setFormSummaryIdList(ids);
        paramForController.setUserId(SecurityUtil.getUserId());
        List<ResultOfExcelGenerator> result = super.createExcelForAdmin(paramForController);
        result.add(this.downSms(excelConfigList, ids));
        return new DownDataVo<>(formSummaryNewList.size(), result);
    }

    /**
     * app端下载
     * @param excelConfigList
     * @param sqfwIdList
     * @return
     */
    public List<ResultOfExcelGenerator> createExcel(List<ExcelCreateConfig> excelConfigList, List<String> sqfwIdList) {
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getSqfwId, "in", sqfwIdList);
        List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query("id", cnd);

        List<String> ids = formSummaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList());

        CompleteFlowExcelParamForController paramForController = new CompleteFlowExcelParamForController();
        paramForController.setExcelCreateConfigList(excelConfigList);
        paramForController.setFormSummaryIdList(ids);
        paramForController.setUserId(SecurityUtil.getUserId());
        List<ResultOfExcelGenerator> result = super.createExcelForAdmin(paramForController);
        result.add(this.downSms(excelConfigList, ids));
        return result;
    }

    /**
     * 后台下载
     * @param excelConfigList
     * @param summaryIdList
     * @return
     */
    public List<ResultOfExcelGenerator> createExcelForAdmin(List<ExcelCreateConfig> excelConfigList, List<String> summaryIdList) {
        CompleteFlowExcelParamForController paramForController = new CompleteFlowExcelParamForController();
        paramForController.setExcelCreateConfigList(excelConfigList);
        paramForController.setFormSummaryIdList(summaryIdList);
        paramForController.setUserId(SecurityUtil.getUserId());
        List<ResultOfExcelGenerator> result =  super.createExcelForAdmin(paramForController);
        // 下载短信
        result.add(this.downSms(excelConfigList, summaryIdList));
        return result;
    }

    @Override
    protected void customerPopularExcelGenerateParam(ExcelGenerateParam excelGenerateParam) {
        ExcelCreateConfig excelCreateConfig = excelGenerateParam.getExcelConfig();

        if (!excelCreateConfig.getCreateExcelFileFlag()) {
            excelGenerateParam.setCustomerParamMap(Map.of("safetyCheckList", Arrays.asList()));
            return;
        }

        // 当涉及到任务状态跟踪时，就需要设置此参数
        if (SafetyCheckEnum.FIRE_SAFETY_INSPECTION.getCode().equals(excelCreateConfig.getFileIdentity())) {
            List<SafetyCheckDTO> safetyCheckList = this.getAllSafetyCheck(excelGenerateParam);
            excelGenerateParam.setCustomerParamMap(Map.of("safetyCheckList", safetyCheckList));
        }
        if (SafetyCheckEnum.THREE_LISTS_OF_SPECIAL_PROJECT.getCode().equals(excelCreateConfig.getFileIdentity())) {
            List<SafetyCheckDTO> safetyCheckList = this.getAllSafetyCheck(excelGenerateParam);
            excelGenerateParam.setCustomerParamMap(Map.of("safetyCheckList", safetyCheckList));
        }
        if (SafetyCheckEnum.GAS_SAFETY_INSPECTION.getCode().equals(excelCreateConfig.getFileIdentity())) {
            List<SafetyCheckDTO> safetyCheckList = this.getAllSafetyCheck(excelGenerateParam);
            excelGenerateParam.setCustomerParamMap(Map.of("safetyCheckList", safetyCheckList));
        }
        if (SafetyCheckEnum.GAS_USAGE_AND_STORAGE.getCode().equals(excelCreateConfig.getFileIdentity())) {
            List<SafetyCheckDTO> safetyCheckList = this.getAllSafetyCheck(excelGenerateParam);
            excelGenerateParam.setCustomerParamMap(Map.of("safetyCheckList", safetyCheckList));
        }
        if (SafetyCheckEnum.GAS_CATERING_USERS.getCode().equals(excelCreateConfig.getFileIdentity())) {
            List<SafetyCheckDTO> safetyCheckList = this.getAllSafetyCheck(excelGenerateParam);
            excelGenerateParam.setCustomerParamMap(Map.of("safetyCheckList", safetyCheckList));
        }
        if (SafetyCheckEnum.FIRE_SAFETY_IMG.getCode().equals(excelCreateConfig.getFileIdentity())) {
            List<SafetyCheckDTO> safetyCheckList = this.getAllSafetyCheck(excelGenerateParam);
            excelGenerateParam.setCustomerParamMap(Map.of("safetyCheckList", safetyCheckList));
        }
    }

    /**
     * 获取所有排查任务(巡查任务复查需要用到)
     * @param excelGenerateParam
     * @return
     */
    private List<SafetyCheckDTO> getAllSafetyCheck(ExcelGenerateParam excelGenerateParam) {

        List<ExcelRowDataParam> dataList = excelGenerateParam.getDataList();

        if (dataList.size() == 0) return new ArrayList<>();

        Set<String> setType = new HashSet<>();
        for (ExcelRowDataParam dataParam : dataList) {
            SafetyCheckDTO safetyCheckDTO = (SafetyCheckDTO) dataParam.getAbstractCustomerPdfCreateField();
            setType.add(safetyCheckDTO.getAttributesOfInspectionUnits());
        }

        StringBuilder sql = new StringBuilder();
        int k = 0;
        for (String s : setType) {
            StringBuilder stringBuilder = new StringBuilder("select param_data from shequ.sqfw_form_summary_new where ");
            stringBuilder.append("(param_data->>'attributesOfInspectionUnits'='"+s+"' and ");
            stringBuilder.append("(param_data->>'placeName',param_data->>'address') in (");
            int i = 0;
            Set<String> set = new HashSet<>();
            for (ExcelRowDataParam dataParam : dataList) {
                SafetyCheckDTO safetyCheckDTO = (SafetyCheckDTO) dataParam.getAbstractCustomerPdfCreateField();
                String value = safetyCheckDTO.getAttributesOfInspectionUnits() + safetyCheckDTO.getPlaceName() + safetyCheckDTO.getAddress();
                if (set.contains(value)) {
                    continue;
                } else {
                    set.add(value);
                }

                if (s.equals(safetyCheckDTO.getAttributesOfInspectionUnits())) {
                    if (i > 0) {
                        stringBuilder.append(",");
                    }
                    stringBuilder.append("('"+safetyCheckDTO.getPlaceName()+"','"+safetyCheckDTO.getAddress()+"')");
                    i ++;
                }
            }
            stringBuilder.append("))");
            if (k > 0) {
                sql.append(" union all ");
            }
            sql.append(stringBuilder);
            k ++;
        }

        List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.listEntity(Sqls.create(sql.toString()));

        List<SafetyCheckDTO> safetyCheckDTOList = new ArrayList<>();
        for (Sqfw_formSummary_new formSummaryNew : formSummaryNewList) {
            SafetyCheckDTO safetyCheckDTO = JSON.parseObject(formSummaryNew.getParamData(), SafetyCheckDTO.class);
            safetyCheckDTOList.add(safetyCheckDTO);
        }

        // 升序
        safetyCheckDTOList = safetyCheckDTOList.stream().sorted(Comparator.comparing(SafetyCheckDTO::getInspectionDate)).collect(Collectors.toList());

        return safetyCheckDTOList;
    }

    @Override
    public List<ExcelGeneratorConfig> getExcelGeneratorConfig(List<ExcelCreateConfig> excelCreateConfigList) {
        List<ExcelGeneratorConfig> generatorConfigList = new ArrayList<>();

        for (ExcelCreateConfig excelCreateConfig : excelCreateConfigList) {

            ExcelGeneratorConfig excelGeneratorConfig = new ExcelGeneratorConfig();

            if (SafetyCheckEnum.NINE_SMALL_DAILY_INSPECTION.getCode().equals(excelCreateConfig.getFileIdentity())) {
                excelGeneratorConfig.setExcelGenerator(new NineSmallExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(excelCreateConfig);
                generatorConfigList.add(excelGeneratorConfig);
            }
            if (SafetyCheckEnum.FIRE_SAFETY_INSPECTION.getCode().equals(excelCreateConfig.getFileIdentity())) {
                excelGeneratorConfig.setExcelGenerator(new ThreeExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(excelCreateConfig);
                generatorConfigList.add(excelGeneratorConfig);
            }
            if (SafetyCheckEnum.GAS_SAFETY_INSPECTION.getCode().equals(excelCreateConfig.getFileIdentity())) {
                excelGeneratorConfig.setExcelGenerator(new GasSafetyExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(excelCreateConfig);
                generatorConfigList.add(excelGeneratorConfig);
            }
            if (SafetyCheckEnum.GAS_USAGE_AND_STORAGE.getCode().equals(excelCreateConfig.getFileIdentity())) {
                excelGeneratorConfig.setExcelGenerator(new GasUseAndStorageExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(excelCreateConfig);
                generatorConfigList.add(excelGeneratorConfig);
            }
            if (SafetyCheckEnum.GAS_CATERING_USERS.getCode().equals(excelCreateConfig.getFileIdentity())) {
                excelGeneratorConfig.setExcelGenerator(new UrbanGasCateringExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(excelCreateConfig);
                generatorConfigList.add(excelGeneratorConfig);
            }
            if (SafetyCheckEnum.KEY_UNIT_OF_FIRE_SAFETY.getCode().equals(excelCreateConfig.getFileIdentity())) {
                excelGeneratorConfig.setExcelGenerator(new KeyUnitOfFireSafetyExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(excelCreateConfig);
                generatorConfigList.add(excelGeneratorConfig);
            }
            if (SafetyCheckEnum.FIRE_SAFETY_IMG.getCode().equals(excelCreateConfig.getFileIdentity())) {
                excelGeneratorConfig.setExcelGenerator(new HiddenImgExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(excelCreateConfig);
                generatorConfigList.add(excelGeneratorConfig);
            }
            if (SafetyCheckEnum.THREE_LISTS_OF_SPECIAL_PROJECT.getCode().equals(excelCreateConfig.getFileIdentity())) {
                excelGeneratorConfig.setExcelGenerator(new SpecialProjectThreeExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(excelCreateConfig);
                generatorConfigList.add(excelGeneratorConfig);
            }
        }

        return generatorConfigList;
    }

    @Override
    public AbstractCustomerPdfCreateField getAbstractCustomerField(String jsonStr) {
        return JSONObject.parseObject(jsonStr, SafetyCheckDTO.class);
    }

    /**
     * 下载短信
     * @param excelConfigList
     * @param ids
     * @return
     */
    private ResultOfExcelGenerator downSms(List<ExcelCreateConfig> excelConfigList, List<String> ids) {
        for (ExcelCreateConfig excelCreateConfig : excelConfigList) {
            if (SafetyCheckEnum.SMS.getCode().equals(excelCreateConfig.getFileIdentity())) {
                // 是否数据检测 false为数据检测
                Boolean createExcelFileFlag = excelCreateConfig.getCreateExcelFileFlag();
                // 是否生成模板 true为生成模板
                Boolean onlyGenerateTemplateFlag = excelCreateConfig.getOnlyGenerateTemplateFlag();

                ResultOfExcelGenerator result = new ResultOfExcelGenerator();

                result.setFileIdentity(excelCreateConfig.getFileIdentity());

                // 数据检测
                if (!createExcelFileFlag) {
                    int dataCheck = sqfwSmsMsgService.dataCheck(ids);
                    if (dataCheck > 0) {
                        result.setPassCreateConditionFlag(true);
                    } else {
                        result.setPassCreateConditionFlag(false);
                    }
                    return result;
                }

                // 下载模板
                if (onlyGenerateTemplateFlag) {
                    String url = sqfwSmsMsgService.downExcel(ids, true);
                    result.setExcelUrl(url);
                    return result;
                }

                // 下载数据
                String url = sqfwSmsMsgService.downExcel(ids, false);
                result.setExcelUrl(url);
                return result;
            }
        }
        return null;
    }
}
